package com.supos.progress.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

public class FileUtil {
    public static void uploadFile(byte[] file,String fileName) throws IOException {
        File targetFile = new File(Constants.filePath);
        if (!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream outputStream = new FileOutputStream(Constants.filePath+"/excel/"+fileName);
        outputStream.write(file);
        outputStream.flush();
        outputStream.close();
    }

    public static void uploadMultiFile(List<MultipartFile> files) throws IOException {
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i=0;i<files.size();++i){
            file = files.get(i);
            if (!file.isEmpty()){
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(new FileOutputStream(new File(Constants.filePath+"/images/"+file.getOriginalFilename())));
                stream.write(bytes);
                stream.close();
            }
        }
    }

    public static List<String> getNames(){
        File file = new File(Constants.filePath+"/images/");
        File[] files = file.listFiles();
        List<String> names = new ArrayList<>();
        Arrays.stream(files).forEach(r->{
            names.add("/images/"+r.getName());
        });
        return names;
    }

    public static List<Map<String,Object>> getExcelNames(){
        File file = new File(Constants.filePath+"/excel/");
        File[] files = file.listFiles();
        List<Map<String,Object>> names = new ArrayList<>();
        Arrays.stream(files).forEach(r->{
            String name = r.getName();
            Map<String,Object> res = new HashMap<>();
            res.put("value",name);
            for (MonthEnum monthEnum:MonthEnum.values()){
                if (monthEnum.getName().equals(name.substring(name.indexOf("-")+1,name.indexOf(".")))){
                    res.put("label",monthEnum.getLabel());
                    break;
                }
            }
            names.add(res);
        });
        return names;
    }
}
